# -*- coding: UTF-8 -*-
import os
import yaml
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def action(config, run_date):
    # 解析配置文件
    conf = config['akshare']['stocks']['CN']
    push_methods = conf['push_methods']

    file_path = 'data/akshare/stocks/CN'
    for method in push_methods:
        if method == 'email':
            process_email(f'{file_path}/result-{run_date}.csv')

def process_email(result_path):
    if not os.path.exists(result_path):
        return
    with open(result_path, 'r') as file:
        lines = file.readlines()
    content = ''.join(lines)
    if not content:
        return

    # 加载邮件服务器的配置信息
    with open('conf/email.yaml', 'r') as file:
        mail = yaml.safe_load(file)['email']

    msg = MIMEText(content, 'html', 'UTF-8')
    msg['Subject'] = '到价提醒'
    msg['From'] = mail['smtp_user']
    msg['To'] = ';'.join(mail['recipients'])

    try:
        server = smtplib.SMTP_SSL(mail['smtp_host'], int(mail['smtp_port']))
        server.login(mail['smtp_user'], mail['smtp_pswd'])
        server.sendmail(mail['smtp_user'], mail['recipients'], msg.as_string())
        server.quit()
        print('send mail successfull')
    except Exception as e:
        print(f"Error: Unable to send email. {e}")

def main():
    result_path = '/tmp/result-20241216.csv'
    process_email(result_path)


if __name__ == '__main__':
    main()
